package com.ah._03part;

import com.ah._03part.domain.Order;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;

/**
 * 生产者
 */
public class Produce {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        //创建生产者对象
        DefaultMQProducer dmp = new DefaultMQProducer("part_produce_group");
        //设置命名空间地址
        dmp.setNamesrvAddr("192.168.19.132:9876");
        //启动生产者
        dmp.start();

        List<Order> orders = orderList();
        //循环消息对象
        for (Order order : orders) {
        //创建消息对象
            Message message = new Message("part_topic", "", order.toString().getBytes());

            //发送消息，并选择消息队列
            SendResult result = dmp.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    /**
                     * 让相同订单id的消息选择同一个队列
                     * orderId % list.size()
                     */
                    //根据订单id选择队列
                    int index = (int) ((Long) o % list.size());

                    return list.get(index);
                }
            },order.getOrderId());
            System.out.println("result = " + result);
        }


        //关闭生产者impletopic
        dmp.shutdown();
    }

//    生产很多订单的方法
    public static List<Order> orderList(){
        List<Order> orders= new ArrayList<>();
        //准备订单信息
        orders.add(new Order(3L,"创建订单"));
        orders.add(new Order(1L,"创建订单"));
        orders.add(new Order(1L,"支付订单"));
        orders.add(new Order(3L,"支付订单"));
        orders.add(new Order(4L,"创建订单"));
        orders.add(new Order(2L,"创建订单"));
        orders.add(new Order(2L,"支付订单"));
        orders.add(new Order(4L,"支付订单"));
        orders.add(new Order(1L,"订单完成"));
        orders.add(new Order(3L,"订单完成"));
        orders.add(new Order(4L,"订单完成"));
        orders.add(new Order(2L,"订单完成"));

        return orders;

    }

}
